package com.qf.controller;/*
 *保护你的大熊
 *2021/11/26
 *11:40
 */

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.annotation.RequiresPermissionsDesc;
import com.qf.pojo.DtsAdmin;
import com.qf.service.AdminAdminService;
import com.qf.util.AdminResponseCode;
import com.qf.util.AdminResponseUtil;
import com.qf.util.ResponseUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin("*")
@RestController
@RequestMapping("/admin/admin")
public class AdminAdminController {

    @Autowired
    AdminAdminService adminService;


    @RequiresPermissions("admin:admin:delete")
    @RequiresPermissionsDesc(menu = { "系统管理", "管理员管理" }, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody DtsAdmin admin){
        if (admin == null) {
            return ResponseUtil.badArgument();
        }

        if(adminService.deleteById(admin.getId()) == 0){
            ResponseUtil.fail();
        }

        return ResponseUtil.ok();
    }


    @RequiresPermissions("admin:admin:update")
    @RequiresPermissionsDesc(menu = { "系统管理", "管理员管理" }, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody DtsAdmin admin){
        if (admin == null) {
            return ResponseUtil.badArgument();
        }

        admin = adminService.update(admin);

        return ResponseUtil.ok(admin);
    }


    @RequiresPermissions("admin:admin:create")
    @RequiresPermissionsDesc(menu = { "系统管理", "管理员管理" }, button = "添加")
    @PostMapping("/create")
    public Object add(@RequestBody DtsAdmin admin){
        if (admin == null) {
            return ResponseUtil.badArgument();
        }

        if( ! adminService.findByUsername(admin.getUsername())){
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_NAME_EXIST);
        }

        admin = adminService.insert(admin);

        return ResponseUtil.ok(admin);
    }


    @RequiresPermissions("admin:admin:list")
    @RequiresPermissionsDesc(menu = { "系统管理", "管理员管理" }, button = "查询")
    @GetMapping("/list")
    public Object list(
            @RequestParam(name = "page",required = false,defaultValue = "1") Integer page,
            @RequestParam(name = "limit",required = false,defaultValue = "20") Integer limit,
            String username,
            @RequestParam(name = "sort",required = false,defaultValue = "add_time") String sort,
            @RequestParam(name = "order",required = false,defaultValue = "asc") String order){

        IPage<DtsAdmin> iPage = adminService.queryPage(page,limit,username,sort,order);

        Map<String,Object> data = new HashMap<>();
        data.put("total", iPage.getTotal());
        data.put("items", iPage.getRecords());
        return ResponseUtil.ok(data);
    }
}
